<!--
 * @Description: 只读表单的公共组件
 * @Author: li.e.zhang
 * @Date: 2022-03-11 15:34:09
 * @LastEditors: li.e.zhang
 * @LastEditTime: 2022-03-22 14:01:43
 * ==================配置说明==================
 * formData: Object // 表单值，必传字段
 * formItems: Array // 表单项，必传字段
 * formRows: Array // 表单布局配置（每行放多少个表单项），必传字段

 * ===============formItems配置项==============
 *   {
 *       label: String // 必填，表单项label
 *       disabledI18n: Boolean // 是否禁用国际化 true: 原样显示label; false: 国际化后显示
 *       key: String // 必填，对应表单项内容的字段名
 *       class: String // 样式类名
 *       format: Function(value) // 自定义文字内容 value: 回传的表单项数据
 *   }
 * ]
-->

<template>
    <div
        v-loading.fullscreen.lock="pageData.imgLoading"
        class="readonly-form"
    >
        <el-form
            :model="pageData.pageFormData"
            :class="`otd-order-detail-form-show readonly-form ${formClassName}`"
        >
            <div
                v-for="(row, index) in pageFormItems"
                :key="index"
                class="row"
            >
                <el-form-item
                    v-for="item in row"
                    :key="item.key"
                    :label="item.disabledI18n ? item.label : `${$t(item.label)}: `"
                    :prop="item.key"
                    :class="`${item.class || ''} ${item.type === 'upload' ? 'upload-item' : ''}`"
                >
                    <!-- 表单项自定义 -->
                    <template v-if="item.slot">
                        <slot
                            :name="item.key"
                        />
                    </template>
                    <!-- 表单数据格式化 -->
                    <template v-else-if="item.formatValue">
                        {{ typeof item.formatValue === "function" ? item.formatValue(pageData.pageFormData[item.key]) : pageData.pageFormData[item.key] }}
                    </template>
                    <!-- 表单数据格式化: 往后不使用 -->
                    <template v-else-if="item.format">
                        {{ typeof item.format === "function" ? item.format(pageData.pageFormData[item.key]) : pageData.pageFormData[item.key] }}
                    </template>
                    <!-- 文件 -->
                    <template v-else-if="item.type === 'upload'">
                        <el-upload
                            ref="uploadRef"
                            v-model:file-list="pageData.pageFormData[item.key]"
                            class="upload-box"
                            action="#"
                            :with-credentials="true"
                            :on-preview="(file) => handleFilePreview(file, item.previewApi)"
                        />
                        <el-image-viewer
                            v-if="pageData.srcList.length > 0"
                            :initial-index="0"
                            :url-list="pageData.srcList"
                            @close="closeImgPreview"
                        />
                    </template>
                    <!-- 价格 -->
                    <template v-else-if="item.type === 'price'">
                        {{ pageData.pageFormData[item.key] ? (item.showCurrency ? DEFAULT_CURRENCY : '') + pageData.pageFormData[item.key] : '' }}
                    </template>
                    <!-- 正常展示 -->
                    <template v-else>
                        {{ pageData.pageFormData[item.key] }}
                    </template>
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script>
// 插件
import { computed, reactive, watch } from 'vue'
import { useStore } from 'vuex'
import { useI18n } from 'vue-i18n'
import ObsClient from 'esdk-obs-browserjs/src/obs'
import { ElMessage } from 'element-plus'
import { DEFAULT_CURRENCY } from '@/enum/system-common-enum'

export default {
    name: 'ReadonlyForm',
    props: {
        // 表单数据
        formData: {
            type: Object,
            required: true,
            default: () => {
                return {}
            }
        },
        // 表单项
        formItems: {
            type: Array,
            required: true,
            default: () => {
                return []
            }
        },
        // 表单布局 每行展示多少个表单项
        formRows: {
            type: Array,
            required: true,
            default: () => {
                return []
            }
        },
        // 表单样式类名
        formClassName: {
            type: String,
            default: ''
        }
    },
    setup (props) {
        const { t } = useI18n()
        const store = useStore()
        /* 定义变量 */
        const pageData = reactive({
            pageFormData: props.formData,
            acceptImageType: ['.JPG', '.JPEG', '.PNG', '.jpg', '.jpeg', '.png'],
            imgLoading: false, // 图片预览时的loading
            srcList: [] // 图片预览数据
        })

        // 按照布局配置 组装表单项
        const pageFormItems = computed(() => {
            const tempData = []
            // slice 遇到引用数据类型时是浅拷贝，但此处不会修改数组中的值，所以暂时没影响
            const tempFormItems = props.formItems.slice(0, props.formItems.length).filter(item => {
                return !item.hasOwnProperty('isHidden') ||
                    (typeof item.isHidden === 'boolean' && !item.isHidden) ||
                    (typeof item.isHidden === 'function' && !item.isHidden(item, props.formData[item.key]))
            })
            props.formRows.forEach(rowItemQuantity => {
                tempData.push(tempFormItems.splice(0, rowItemQuantity))
            })
            return tempData
        })

        /**
         * 文件预览或下载
         */
        const handleFilePreview = async (file, previewApi) => {
            if (typeof previewApi === 'string' && previewApi.includes('obsClientOfhuaweiCloudInfo')) {
                const apiType = previewApi.split('-')
                // 获取华为云用的access_key_id  access_key_id  server
                const warrantyDealerInfo = await store.dispatch('retailOrder/gethuaweiCloudInfo', apiType[1])
                // 创建ObsClient实例
                const obsClient = new ObsClient({
                    access_key_id: warrantyDealerInfo.access,
                    secret_access_key: warrantyDealerInfo.secret,
                    server: warrantyDealerInfo.endpoint,
                    security_token: warrantyDealerInfo.securitytoken
                })
                obsClient.getObject({
                    Bucket: warrantyDealerInfo.bucketName,
                    Key: file.fileKey,
                    SaveByType: 'file'
                }, function (err, result) {
                    if (err) {
                        console.error('Error-->' + err)
                        ElMessage.warning(t('common.operationFailed'))
                    } else {
                        window.open(result.InterfaceResult.Content.SignedUrl)
                    }
                })
            } else {
                const isImage = pageData.acceptImageType.filter(imgType => file.name && file.name.endsWith(imgType)).length > 0
                const code = file?.attachmentCode ? file.attachmentCode : file.response.attachmentCode
                pageData.imgLoading = true
                try {
                    const res = await previewApi(code)
                    if (isImage) {
                        let fileType = file.name.split('.').pop().toUpperCase()
                        if (fileType === 'JPG') {
                            fileType = 'jpeg'
                        }
                        const newFile = await new File([res], file.name, {
                            type: 'image/' + fileType
                        })
                        const createObjectURL = function (blob) {
                            return window[window.webkitURL ? 'webkitURL' : 'URL'].createObjectURL(blob)
                        }
                        pageData.srcList = [createObjectURL(newFile)]
                    } else {
                        downloadFile({ blob: res, name: file.name })
                    }
                    // if (isImage) {
                    //     const createObjectURL = function (blob) {
                    //         return window[window.webkitURL ? 'webkitURL' : 'URL'].createObjectURL(blob)
                    //     }
                    //     pageData.srcList = [createObjectURL(res)]
                    // } else {
                    //     downloadFile({ blob: res, name: file.name })
                    // }
                    pageData.imgLoading = false
                } catch {
                    pageData.imgLoading = false
                }
            }
        }

        /**
         * 下载文件
         * @param blob
         * @param name
         */
        const downloadFile = ({ blob, name }) => {
            if (blob.type === 'application/json') {
                // 如果返回的是json 没有下载权限没有返回流
                const reader = new FileReader()
                reader.readAsText('utf-8')
                reader.onload = () => {
                    // const resJson = JSON.parse(reader.result);
                    // if (resJson.resCode === 1) message.error(resJson.resMsg);
                }
                return
            }
            if (window.navigator.msSaveOrOpenBlob) {
                navigator.msSaveBlob(blob, name)
            } else {
                // const type = name.split('.').pop().toLowerCase()
                // if (type === 'pdf' || type === 'txt') {
                //     const filterType = [
                //         { suffix: 'pdf', mime: 'application/pdf' },
                //         { suffix: 'txt', mime: 'application/json' }
                //     ]
                //     const typeMine = filterType.find(item => {
                //         return item.suffix === type
                //     })

                //     const blobPDF = new Blob([blob], { type: typeMine.mime })
                //     const url = URL.createObjectURL(blobPDF)
                //     window.open(url)
                //     URL.revokeObjectURL(url) // 释放url
                // } else {
                const link = document.createElement('a')
                const evt = document.createEvent('MouseEvents')
                link.style.display = 'none'
                link.href = window.URL.createObjectURL(blob)
                link.download = name
                document.body.appendChild(link)
                evt.initEvent('click', false, false)
                link.dispatchEvent(evt)
                document.body.removeChild(link)
                // }
            }
            closeImgPreview()
        }

        /**
         * 关闭图片预览
         */
        const closeImgPreview = () => {
            pageData.srcList = []
        }

        /* 监听 */
        watch(() => props.formData, (newValue, oldValue) => {
            pageData.pageFormData = newValue
        })

        /* 返回 */
        return {
            pageData,
            pageFormItems,
            handleFilePreview,
            closeImgPreview,
            DEFAULT_CURRENCY
        }
    }
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/order-to-delivery/order-detail-page/form-show.scss";

:deep(.el-form-item__content) {
    color: black!important;
}

.readonly-form {
    .el-form-item {
        &.upload-item {
            flex-direction: column;
            flex-grow: unset !important;
            :deep .el-form-item__label {
                text-align: left;
            }
            :deep .el-upload-list__item-name {
                color: #3660B2;
            }
            :deep .el-form-item__content {
                .upload-box {
                    .el-upload {
                        display: none;
                    }
                    .el-upload-list {
                        .el-upload-list__item {
                            .el-icon-close-tip {
                                display: none !important;
                            }
                            .el-upload-list__item-status-label {
                                display: none;
                            }
                            .el-icon-close {
                                display: none;
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>
